<template>
  <!-- 无人机管理页面 -->
  <div class="Hcont" v-if="homepage === 2">
    <div class="Hhead" @click="toHcont">
      <div class="hd1">
        <img src="../assets/logo3.png" alt="系统logo" class="hd11">
        <div class="hd12 noselect">
          <div class="hd121">智能配送</div>
          <div class="hd122">Intelligent Distribution</div>
        </div>
      </div>
      <img src="../assets/work.png" alt="工作图标" class="hd2">
      <div class="hd4"></div>
      <div class="hd3">
        <img src="../assets/tou.png" alt="用户头像" class="hd31">
        <el-dropdown>
         <span class="el-dropdown-link noselect xiaoshou" @click.stop>
            Qin<el-icon class="el-icon--right"><ArrowDown /></el-icon>
        </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :icon="Postcard">个人信息</el-dropdown-item>
              <el-dropdown-item :icon="User" @click="customer">AI客服</el-dropdown-item>
              <el-dropdown-item :icon="Setting">设置</el-dropdown-item>
              <el-dropdown-item :icon="Switch">切换账号</el-dropdown-item>
              <el-dropdown-item :icon="SwitchButton">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="hb"></div>
    <div class="Hbody">
      <div class="bdl">
        <div class="bdl1">
          <div class="bdl11 noselect xiaoshou" @click="uav" :class="{ 'active-nav': homepage === 2 }">
            <img src="../assets/UAV.png" alt="无人机图标" class="bdl111">
            <div class="bdl112">无人机管理</div>
          </div>
          <div class="bdl12 noselect xiaoshou" @click="mm" :class="{ 'active-nav': homepage === 3 }">
            <img src="../assets/MM.png" alt="商户图标" class="bdl121">
            <div class="bdl122">商户管理</div>
          </div>
          <div class="bdl13 noselect xiaoshou" @click="task" :class="{ 'active-nav': homepage === 4 }">
            <img src="../assets/task.png" alt="任务图标" class="bdl131">
            <div class="bdl132">任务管理</div>
          </div>
          <div class="bdl14 noselect xiaoshou" @click="map" :class="{ 'active-nav': homepage === 5 }">
            <img src="../assets/map.png" alt="地图图标" class="bdl141">
            <div class="bdl142">地图与空域管理</div>
          </div>
          <div class="bdl15 noselect xiaoshou" @click="alarm" :class="{ 'active-nav': homepage === 6 }">
            <img src="../assets/alarm.png" alt="告警图标" class="bdl151">
            <div class="bdl152">告警中心</div>
          </div>
        </div>
      </div>
      
      <div class="bdr">
        <div class="dashboard-container">
          <div class="filter-bar">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-input 
                  placeholder="搜索无人机编号" 
                  v-model="searchKeyword" 
                  clearable
                >
                  <template #prefix>
                    <Search />
                  </template>
                </el-input>
              </el-col>
              <el-col :span="4">
                <el-select 
                  v-model="statusFilter" 
                  placeholder="筛选状态" 
                  clearable
                >
                  <el-option label="全部" value=""></el-option>
                  <el-option label="在线" value="online"></el-option>
                  <el-option label="离线" value="offline"></el-option>
                  <el-option label="执行任务中" value="tasking"></el-option>
                  <el-option label="维护中" value="maintenance"></el-option>
                </el-select>
              </el-col>
              <el-col :span="2" :offset="12">
                <el-button type="primary" @click="addDrone">
                  <Plus /> 新增无人机
                </el-button>
              </el-col>
            </el-row>
          </div>

          <div class="dashboard-cards" style="margin-top: 20px;">
            <el-card class="dashboard-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span>总数量</span>
                </div>
              </template>
              <div class="card-content">
                <div class="card-value">{{ drones.length }}</div>
                <div class="card-footer">
                  <span class="card-stat">注册无人机总数</span>
                </div>
              </div>
            </el-card>
            
            <el-card class="dashboard-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span>在线率</span>
                </div>
              </template>
              <div class="card-content">
                <div class="card-value">{{ onlineRate }}%</div>
                <div class="card-progress">
                  <el-progress :percentage="onlineRate" color="#409EFF"></el-progress>
                </div>
              </div>
            </el-card>
            
            <el-card class="dashboard-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span>任务中</span>
                </div>
              </template>
              <div class="card-content">
                <div class="card-value">{{ taskingCount }}</div>
                <div class="card-footer">
                  <span class="card-stat">正在执行配送任务</span>
                </div>
              </div>
            </el-card>
            
            <el-card class="dashboard-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span>异常设备</span>
                </div>
              </template>
              <div class="card-content">
                <div class="card-value" style="color: #F56C6C;">{{ errorCount }}</div>
                <div class="card-footer">
                  <span class="card-stat">需要维护或检修</span>
                </div>
              </div>
            </el-card>
          </div>

          <div class="recent-tasks">
            <el-card class="tasks-card" shadow="hover">
              <template #header>
                <div class="tasks-header">
                  <span>无人机列表</span>
                  <div class="header-actions">
                    <el-button type="primary" size="small" @click="viewAllDrones">查看全部</el-button>
                    <span class="card-stat">共 {{ filteredDrones.length }} 台设备</span>
                  </div>
                </div>
              </template>
              <div class="tasks-content">
                <el-table 
                  :data="filteredDrones" 
                  stripe 
                  style="width: 100%;"
                  @row-click="viewDroneDetail"
                >
                  <el-table-column type="index" label="序号" width="60"></el-table-column>
                  <el-table-column prop="id" label="无人机编号">
                    <template #default="scope">
                      <span :class="{ 'grayed-out': isGrayed(scope.row.status) }">{{ scope.row.id }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="model" label="型号">
                    <template #default="scope">
                      <span :class="{ 'grayed-out': isGrayed(scope.row.status) }">{{ scope.row.model }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="status" label="状态">
                    <template #default="scope">
                      <el-tag :type="getStatusTagType(scope.row.status)">
                        {{ formatStatusText(scope.row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="battery" label="电量">
                    <template #default="scope">
                      <div :class="{ 'grayed-out': isGrayed(scope.row.status) }">
                        <el-progress 
                          :percentage="scope.row.battery" 
                          :stroke-width="6" 
                          :color="getBatteryColor(scope.row.battery)"
                          width="100"
                        ></el-progress>
                        <span style="margin-left: 10px">{{ scope.row.battery }}%</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="location" label="当前位置">
                    <template #default="scope">
                      <span :class="{ 'grayed-out': isGrayed(scope.row.status) }">{{ scope.row.location }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="lastActive" label="最后活动时间">
                    <template #default="scope">
                      <span :class="{ 'grayed-out': isGrayed(scope.row.status) }">{{ scope.row.lastActive }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作">
                    <template #default="scope">
                      <el-button type="text" size="small" @click="viewDroneDetail(scope.row)">详情</el-button>
                      <el-button 
                        type="text" 
                        size="small" 
                        @click="controlDrone(scope.row)"
                        :disabled="scope.row.status === 'offline'"
                      >
                        控制
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </div>

    <!-- 无人机详情弹窗 -->
    <el-dialog 
      v-model="droneDetailVisible" 
      title="无人机详情" 
      :width="700"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="drone-photo">
            <img :src="currentDrone.photo" alt="无人机图片" class="drone-img">
          </div>
        </el-col>
        <el-col :span="16">
          <el-descriptions column="1" border>
            <el-descriptions-item label="无人机编号">{{ currentDrone.id }}</el-descriptions-item>
            <el-descriptions-item label="型号">{{ currentDrone.model }}</el-descriptions-item>
            <el-descriptions-item label="购买日期">{{ currentDrone.purchaseDate }}</el-descriptions-item>
            <el-descriptions-item label="累计飞行时间">{{ currentDrone.flightHours }} 小时</el-descriptions-item>
            <el-descriptions-item label="最大负载">{{ currentDrone.maxLoad }} kg</el-descriptions-item>
            <el-descriptions-item label="续航时间">{{ currentDrone.endurance }} 分钟</el-descriptions-item>
            <el-descriptions-item label="当前状态">{{ formatStatusText(currentDrone.status) }}</el-descriptions-item>
            <el-descriptions-item label="最近维护时间">{{ currentDrone.lastMaintenance }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
      <template #footer>
        <el-button @click="droneDetailVisible = false">关闭</el-button>
        <el-button type="primary" @click="gotoMaintenance">安排维护</el-button>
      </template>
    </el-dialog>
  </div>
    
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ref, computed, onMounted } from 'vue'
// 修复：图标组件名统一大写
import {
  ArrowDown, Postcard, User, Setting, Switch, SwitchButton,
  Plus, Search
} from '@element-plus/icons-vue'

// 初始化路由实例（关键修复：确保router可用）
const router = useRouter()
const tableContainer = ref(null)
// 初始化homepage为2（当前页面默认显示）
const homepage = ref(2)

// 无人机管理相关变量
const searchKeyword = ref('')
const statusFilter = ref('')
const droneDetailVisible = ref(false)
const currentDrone = ref({})

// 无人机模拟数据
const drones = ref([
  {
    id: 'UAV-001',
    model: '顺丰方舟-300',
    status: 'tasking',
    battery: 78,
    location: '科技园A区',
    lastActive: '2025-07-14 14:30:22',
    photo: require('@/assets/drone1.png'),
    purchaseDate: '2024-01-15',
    flightHours: 1240,
    maxLoad: 5,
    endurance: 45,
    lastMaintenance: '2025-06-20'
  },
  {
    id: 'UAV-002',
    model: '京东飞侠-200',
    status: 'online',
    battery: 45,
    location: '物流中心停机坪',
    lastActive: '2025-07-14 14:25:10',
    photo: require('@/assets/drone2.png'),
    purchaseDate: '2024-03-20',
    flightHours: 980,
    maxLoad: 3,
    endurance: 30,
    lastMaintenance: '2025-07-05'
  },
  {
    id: 'UAV-003',
    model: '顺丰方舟-300',
    status: 'offline',
    battery: 0,
    location: '未知',
    lastActive: '2025-07-14 10:15:33',
    photo: require('@/assets/drone3.png'),
    purchaseDate: '2024-02-10',
    flightHours: 1560,
    maxLoad: 5,
    endurance: 45,
    lastMaintenance: '2025-06-10'
  },
  {
    id: 'UAV-004',
    model: '美团闪电-100',
    status: 'maintenance',
    battery: 100,
    location: '维修车间',
    lastActive: '2025-07-14 09:00:00',
    photo: require('@/assets/drone4.png'),
    purchaseDate: '2024-05-05',
    flightHours: 750,
    maxLoad: 2,
    endurance: 25,
    lastMaintenance: '2025-07-14'
  },
  {
    id: 'UAV-005',
    model: '京东飞侠-200',
    status: 'online',
    battery: 92,
    location: '商业区B栋楼顶',
    lastActive: '2025-07-14 14:35:47',
    photo: require('@/assets/drone5.png'),
    purchaseDate: '2024-04-30',
    flightHours: 820,
    maxLoad: 3,
    endurance: 30,
    lastMaintenance: '2025-06-30'
  }
])

// 筛选并排序后的无人机列表
const filteredDrones = computed(() => {
  const filtered = drones.value.filter(drone => {
    const matchesKeyword = drone.id.toLowerCase().includes(searchKeyword.value.toLowerCase())
    const matchesStatus = !statusFilter.value || drone.status === statusFilter.value
    return matchesKeyword && matchesStatus
  })
  
  return filtered.sort((a, b) => {
    const getPriority = (status) => {
      if (status === 'online' || status === 'tasking') return 1
      if (status === 'offline' || status === 'maintenance') return 2
      return 3
    }
    
    const priorityA = getPriority(a.status)
    const priorityB = getPriority(b.status)
    
    if (priorityA !== priorityB) {
      return priorityA - priorityB
    } else {
      return a.id.localeCompare(b.id)
    }
  })
})

// 无人机状态统计
const onlineRate = computed(() => {
  const onlineCount = drones.value.filter(d => d.status === 'online' || d.status === 'tasking').length
  return Math.round((onlineCount / drones.value.length) * 100)
})

const taskingCount = computed(() => {
  return drones.value.filter(d => d.status === 'tasking').length
})

const errorCount = computed(() => {
  return drones.value.filter(d => d.status === 'offline' || d.status === 'maintenance').length
})

// 导航切换方法（关键修复：所有方法同时更新homepage和路由）
const toHcont = () => { 
  homepage.value = 1
  router.push('/HomeViews') 
}
const uav = () => { 
  homepage.value = 2
  router.push('/navViews') 
}
const mm = () => { 
  homepage.value = 3
  router.push('/mmViews') 
}
const task = () => { 
  homepage.value = 4
  router.push('/taskViews') // 假设任务管理路由为/taskViews
}
const map = () => { 
  homepage.value = 5
  router.push('/mapViews') // 假设地图路由为/mapViews
}
const alarm = () => { 
  homepage.value = 6
  router.push('/alarmViews') // 假设告警路由为/alarmViews
}

// 无人机状态格式化
const formatStatusText = (status) => {
  const statusMap = {
    online: '在线',
    offline: '离线',
    tasking: '执行任务中',
    maintenance: '维护中'
  }
  return statusMap[status] || status
}

// 状态标签样式
const getStatusTagType = (status) => {
  const typeMap = {
    online: 'success',
    offline: 'danger',
    tasking: 'primary',
    maintenance: 'warning'
  }
  return typeMap[status] || 'info'
}

// 电池颜色判断
const getBatteryColor = (level) => {
  if (level < 20) return '#F56C6C'
  if (level < 50) return '#E6A23C'
  return '#67C23A'
}

// 判断是否需要显示灰色样式
const isGrayed = (status) => {
  return status === 'offline' || status === 'maintenance'
}

// 无人机操作方法
const viewDroneDetail = (drone) => {
  currentDrone.value = { ...drone }
  droneDetailVisible.value = true
}

const controlDrone = (drone) => {
  alert(`控制无人机 ${drone.id}（${drone.model}）的操作界面`)
}

const addDrone = () => {
  alert('打开新增无人机表单')
}

const gotoMaintenance = () => {
  alert(`为无人机 ${currentDrone.value.id} 安排维护`)
}

// 查看全部无人机
const viewAllDrones = () => {
  homepage.value = 2
  searchKeyword.value = ''
  statusFilter.value = ''
}

// AI客服跳转
const customer = async () =>{
  router.push("/chatViews")
}

onMounted(() => {
  if (tableContainer.value) {
    const containerHeight = tableContainer.value.clientHeight
    tableContainer.value.style.height = `${containerHeight}px`
    tableContainer.value.style.overflow = 'auto'
  }
})
</script>

<style>
/* 样式保持不变 */
.Hcont{
    border-radius: 20px;
    display: flex;
    flex-direction: column;
    width: 97vw;
    height: 98vh;
    overflow: hidden;
    background-color: rgb(239, 239, 238);
}
.Hhead{
  height: 100px;
  width: 100%;
  background-color: rgb(86, 119, 231);
  display: flex;
  flex: none;
  align-items: center;
}
.hd1{
  display: flex;
  margin-left: 60px;
}
.hd11{
  width: 60px;
  border-radius: 100%;
  margin-right: 20px;
}
.hd12{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.hd121{
  font-size: 24px;
  font-weight: 500;
  letter-spacing: 3px;
  color: white;
}
.hd122{
  font-size: 12px;
  color: white;
}
.hd2{
  margin-left: 100px;
  width: 70px;
  margin-top: 30px;
}
.hd3{
  margin-right: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.hd31{
  width: 50px;
  border-radius: 100%;
  margin-right: 10px;
}
.el-dropdown-link{
  color: white;
   outline: none;
}
.hd4{
  flex: 1;
}
.hb{
  width: 100%;
  height: 1px;
  flex: none;
}
.Hbody{
   display: flex;
  flex: 1;
  min-height: 0;
  overflow: hidden;
}
.bdl{
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 280px;
  background-color: rgb(30, 58, 138);
}
.bdl1{
  display: flex;
  flex-direction: column;
  width: 100%;
  align-items: center;
  margin-top: 50px;
}
.bdl11,.bdl12,.bdl13,.bdl14,.bdl15{
  width: 100%;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}
.bdl11:hover,.bdl12:hover,.bdl13:hover,.bdl14:hover,.bdl15:hover{
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px); 
  background-color: rgb(156, 188, 249);
  border-radius: 10px;
}
.bdl11:active,.bdl12:active,.bdl13:active,.bdl14:active,.bdl15:active{
  transform: scale(0.97);
  box-shadow: 0 4px 6px -1px rgba(93, 102, 122, 0.1);
}
.bdl111,.bdl121,.bdl131,.bdl141,.bdl151{
  width: 20px;
  padding-right: 10px;
}
.bdl112,.bdl122,.bdl132,.bdl142,.bdl152{
  font-size: 24px;
  font-weight: 400;
  color: white;
}
.active-nav {
  background-color: rgb(156, 188, 249);
  border-radius: 10px;
}
.bdr {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.dashboard-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}
.dashboard-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}
.dashboard-card {
  height: 180px;
  min-width: 200px;
}
.card-header {
  display: flex;
  align-items: center;
}
.card-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  justify-content: space-between;
}
.card-value {
  font-size: 36px;
  font-weight: 500;
  margin: 10px 0;
}
.card-progress {
  margin-bottom: 10px;
}
.card-footer {
  color: #909399;
  font-size: 14px;
}
.recent-tasks {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 300px;
}
.tasks-card {
   flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.tasks-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.tasks-content {
   flex: 1;
  overflow: auto;
}
.tasks-content > .el-table {
  height: 100%;
}
.filter-bar {
  margin-top: 10px;
  margin-bottom: 10px;
}
.drone-photo {
  display: flex;
  justify-content: center;
  padding: 20px;
}
.drone-img {
  width: 100%;
  max-width: 200px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.el-table .el-progress {
  margin: 0;
}
.el-table .el-button--text {
  padding: 5px 10px;
}
.el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
}
.el-descriptions__label {
  font-weight: 500;
}
.grayed-out {
  color: #909399;
  filter: grayscale(100%);
}
.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>